import axios from 'axios'
import qs from 'qs'

axios.interceptors.response.use(response => {
  // if (response.headers['content-type'].indexOf('json') === -1) {
  //   return {success: false, msg: '登录状态失效，请清除Cookie重新登录！'}
  // }
  return response.data
}, error => {

  if (error.response) {
    let status = error.response.status
    switch (status) {
      case 403:
        return {success: false, msg: 'Sorry, 无权限操作！'}
      case 404:
        return {success: false, msg: 'Sorry, 服务不存在！'}
      case 500:
      case 502:
      case 503:
        return {success: false, msg: 'Sorry, 服务器异常！'}
      case 504:
        return {success: false, msg: 'Sorry, 请求超时！'}
      default:
        return {success: false, msg: 'Sorry, 服务器错误！'}
    }
  }
  return {success: false, msg: 'Sorry, 页面错误！'}
})
let ABS_PATH = process.env.VUE_APP_BASE_API
const Ajax = {
  ajax (url, params, opts={}) {
    url = ABS_PATH + url
    let config = {url: url, method: 'post', responseType: 'json', timeout: 60000}

    var uuid = '';


    if(localStorage.getItem('uuid')){
      uuid = localStorage.getItem('uuid');
    }

    if(opts.headers){
      opts.headers['uuid'] = uuid;
    }else{
      opts.headers = {'uuid':uuid,'Content-Type':'application/x-www-form-urlencoded'};
    }

    if (opts) {
      config = {...config, ...opts}
    }
    if (config['method'] === 'post') {
      if(opts && opts.headers && opts.headers['Content-Type'] == 'application/json'){
        config['data'] = JSON.stringify(params);
      }else{
        config['data'] = qs.stringify(params)
      }
    } else {
      config['params'] = params
    }



    // return new Promise((resolve, reject) => {
    //   axios(config).then(res => {
    //     resolve.apply(this,[res]);
    //   })
    // })
    return axios(config)
  },
  get (url, params, opts) {
    if (opts) {
      opts = Object.assign(opts, {method: 'get'})
    } else {
      opts = {method: 'get'}
    }
    return this.ajax(url, params, opts)
  },
  post (url, params, opts) {
    if (opts) {
      opts = Object.assign(opts, {method: 'post'})
    } else {
      opts = {method: 'post'}
    }
    return this.ajax(url, params, opts)
  }
}
export default Ajax
